//默认设置如下：
var defaultSettings = {
    isAllCheck:false,//关闭全部检查
    isBlurCheck:false,//关闭blur验证
    isInputCheck:false,//关闭输入时验证
    isAjax:false,//关闭ajax提交表单
    ajaxMethod:'get',//默认ajax提交方式为get
    callback:function(data){},//默认回调函数为空(使用jquery的ajax)
    beforesubmit:function(){}//默认提交前执行函数为空(使用jquery的ajax)
}

//构造函数
var Valid = function(em,settings){
    Valid.vSettings = Object.assign(defaultSettings,settings)
    Valid.form = em[0]
    Valid.temparr = []
    Valid.funs.init()
    Valid.validPower = 1//其中一项不通过减一
    Valid.beforeCheckStatus = false
}

// 构造函数的子方法
Valid.funs = {
    //初始化
    init:function(){
        var form = Valid.form

        //查找所有匹配的表单元素
        Valid.funs.find_form_element()

        //绑定提交前验证的事件
        Valid.funs.beforeCheck()

        //表单提交事件监听
        $(form).submit(function(){
            //提交前执行函数
            Valid.funs.beforesubmit()
            //提交后的回调函数
            return Valid.vSettings.isAjax ? false : Valid.beforeCheckStatus
        })

        //是否ajax提交
        if(Valid.vSettings.isAjax){
            Valid.funs.vAjax()
        }
    },
    //查找提交按钮
    find_submit_btn:function(){
        if(Valid.submitBtn){
            return $(Valid.submitBtn)
        }else{
            return $(Valid.form).find('[type=submit]') || $(Valid.form).find('[type=button]') 
        }
    },
    //查找表单元素
    find_form_element:function(){
        var a = Valid.form
        for(var i = 0;i<a.length;i++ ){
            if($(a[i]).attr('required')){
                $(a[i]).attr('novalidate','true')//禁用默认验证样式
                Valid.temparr['required'+i] = a[i]
            }
            if($(a[i]).attr('data-reg')){
                Valid.temparr['dataReg'+i] = a[i]
            }
            if($(a[i]).attr('type')=='checkbox'&&$(a[i]).attr('check-class')){
                var name = $(a[i]).attr('check-class')
                if(typeof(Valid.temparr['checkGroup'+name])=='undefined'){
                    Valid.temparr['checkGroup'+name] = []
                }
                Valid.temparr['checkGroup'+name].push(a[i])
            }
            if($(a[i]).attr('type')=='checkbox'&&$(a[i]).attr('check-single')){
                Valid.temparr['checkSingle'+i] = a[i]
            }
        }
    },
    beforeCheck:function(){

        //提交按钮点击验证
        Valid.funs.find_submit_btn().on('click',function(){
            Valid.beforeCheckStatus = Valid.funs.checkAll()
        })

        // blur
        if(Valid.vSettings.isBlurCheck){
            for(var key in Valid.temparr){
                var inputElm = Valid.temparr[key]
                $(inputElm).on('blur',function(){
                    Valid.beforeCheckStatus = Valid.funs.checkSingle(key,inputElm)
                })
            }
        }

        //输入
        if(Valid.vSettings.isInputCheck){
            for(var t in Valid.temparr){
                var tempelm = Valid.temparr[t]
                $(tempelm).on('input propertychange',function(){
                    Valid.beforeCheckStatus = Valid.funs.checkAll()
                })
            }
        }

    },
    //验证检查全部表单元素
    checkAll:function(){
        for(var key in Valid.temparr){
            var inputElm = Valid.temparr[key]
            // console.log(inputElm)
            var res = Valid.funs.checkSingle(key,inputElm)
            // console.log(res)
            if(res===false){return false}
        }

        //全部通过返回true
        return true
    },
    //检查单个表单元素
    checkSingle:function(key,inputElm){

        var requiredReg = new RegExp('required','i')
        var dataRegReg = new RegExp('dataReg','i')
        var checkGroupReg = new RegExp('checkGroup','i')
        var checkSingle = new RegExp('checkSingle','i')
        var required_res = true,
            datareg_res = true,
            checkgroup_res = true,
            single_res = true

        // required的
        if(requiredReg.test(key)){

            if($(inputElm).val()==''){
                var requiredMsg = $(inputElm).attr('required-msg')
                Valid.funs.showcheckmsg(requiredMsg,inputElm)
                required_res = false
            }

            if(!required_res&&!Valid.vSettings.isAllCheck){
                return false
            }
        }

        // data-reg的
        if(dataRegReg.test(key)){
            var regstr = $(inputElm).attr('data-reg')
            var regmsg = $(inputElm).attr('reg-msg')
            //分离每个正则
            var fengereg = new RegExp("&&","gi")
            if(fengereg.test(regstr)){
                var regarr = regstr.split('&&')
                var regMsgArr = regmsg.split('&&')
                //逐个正则匹配，不匹配则执行回调函数并跳出

                var tempPower = true
                $(regarr).each(function(i,r){
                    var reg = new RegExp(r,'i')
                    var val = $(inputElm).val()
                    if(!reg.test(val)){
                        Valid.funs.showcheckmsg(regMsgArr[i],inputElm)
                        tempPower = false
                        if(tempPower<1){return false}//检验不通过，里面的循环跳出，外面循环跟住跳出
                    }
                })

                if(!tempPower){
                    datareg_res = false
                }
            }else{
                var regsingle = new RegExp(regstr,'i')
                if(!regsingle.test($(inputElm).val())){
                    Valid.funs.showcheckmsg(regmsg,inputElm)
                    datareg_res = false
                }
            }

            if(!datareg_res&&!Valid.vSettings.isAllCheck){
                return false
            }
        }

        // checkGroup的
        if(checkGroupReg.test(key)){
            var temp_power = 0;
            $(inputElm).each(function(index,elm){
                if($(elm).prop('checked')){temp_power ++}
            })

            if(temp_power==0){
                var checkedMsg = '至少勾选'+$(inputElm[0]).attr('check-class')+'中的一项';
                Valid.funs.showcheckmsg(checkedMsg,inputElm)
                checkgroup_res = false
            }

            if(!checkgroup_res&&!Valid.vSettings.isAllCheck){
                return false
            }
        }

        //checkSingle的
        if(checkSingle.test(key)){
            var checkSingleMsg = $(inputElm).attr('check-single-msg')
            if(!$(inputElm).prop('checked')){
                Valid.funs.showcheckmsg(checkSingleMsg,inputElm)
                single_res = false
            }

            if(!single_res&&!Valid.vSettings.isAllCheck){
                return false
            }
        }
        return required_res&&datareg_res&&checkgroup_res&&single_res
    },
    vAjax:function(){
        var form = Valid.form
        var url = $(form).attr('action')
        var method = Valid.vSettings.ajaxMethod
        Valid.funs.find_submit_btn().on('click',function(){
            console.log('in click event')
            if(Valid.beforeCheckStatus){
                $.ajax({
                    'url':url,
                    'method':method,
                    'dataType':Valid.vSettings.ajaxDatatype,
                    'beforeSend':Valid.funs.beforesubmit,
                    'success':Valid.funs.callback
                })  
            }
        })
    },
    //提交前执行
    beforesubmit:function(em){
        // //提交前再检查验证
        // Valid.funs.checkAll()
        //提交前执行函数
        Valid.vSettings.beforesubmit()
    },
    //提交后回调函数
    callback:function(){
        Valid.vSettings.callback()
    },
    //验证信息显示
    showcheckmsg:function(checkmsg,elm){
        alert(checkmsg)
    },
    getkey:function(key){
        return Valid.vSettings[key]
    }
}

//构造函数原型
Valid.prototype = {
    sayname:function(key){
        var name = Valid.funs.getkey.call(this,key)
        alert(name)
    },

}

// jquery原型中定义demo
$.fn.valid = function(settings){
    return new Valid(this,settings)
}